<!-- 添加装备 -->
<template>
  <div class="equip_edit">
    <!-- 标题 -->
    <div style="overflow: hidden;">
      <h2 class="title"> {{isId ? '修改' : '添加'}}装备： </h2>
    </div>
    <!-- 表单 -->
    <el-form :model="form">
      <el-form-item label="装备名称">
        <el-row>
          <el-col :span="8">
            <el-input v-model="form.name" placeholder="请输入装备名称"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="装备图标">
        <el-row>
          <el-col :span="3">
            <upload @uploadUrl="uploadUrl" :icon="form.icon" index="1" />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="装备类型">
        <el-row>
          <el-col :span="3">
            <el-autocomplete
              class="inline-input"
              v-model="form.type"
              :fetch-suggestions="querySearch"
              placeholder="请输入内容">
            </el-autocomplete>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item v-for="(item, i) in data" :key="i" :label="item.label">
        <el-row>
          <el-col :span="7">
            <el-input v-model="form[item.name]" :type="item.type" :placeholder="item.placeholder"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-row>
          <el-col :span="6">
            <el-button type="primary" @click="Ok">确定</el-button>
            <el-button>取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { defineComponent, onMounted, reactive, toRefs, ref, computed } from "vue";
import { useRouter } from 'vue-router';
import Upload from '../../components/Upload.vue';
import axios from '../../http/axios';
import { ElMessage } from 'element-plus';

export default defineComponent ({
  name: 'EquipEdit',
  props: ['id'],
  components: { Upload },
  setup (props) {
    const content = reactive({
      router: useRouter(),
      form: {
        name: '',
        icon: '',
        type: '',
        content: '',
        active: '',  // 主动
        passive: '',  // 被动
      },
      data: [
        { name: 'content', label: '装备描述', placeholder: '请输入装备的主动属性', type:'textarea' },
        { name: 'active', label: '装备主动', placeholder: '请选择装备类型', type:'textarea' },
        { name: 'passive', label: '装备被动', placeholder: '请输入装备的被动属性', type:'textarea' },
      ],
      isId: computed(() => {
        return props.id ? true : false;
      })
    })

    // 带输入建议 
    const { restaurants, loadAll, querySearch } = autocomplete();

    // 接收子组件传递的 图片url
    function uploadUrl ([url]) {
      content.form.icon = url;
    }

    // 提交创建请求
    async function create() {
      const { data, status } =  await axios.post('equips', content.form);
      status === 201 ? ElMessage.success(data.success) : ElMessage.success(data.success);
      content.router.push('/equips/list');
    }

    // 修改时，获取装备数据
    async function getById() {
      const { data, status } = await axios.get(`equips/${props.id}`);
      content.form = data;
      status === 200 ? ElMessage.success('获取成功') : ElMessage.success('获取失败');
    }

    // 提交修改请求
    async function put() {
      const { data, status } = await axios.put(`equips/${props.id}`, content.form);
       status === 200 ? ElMessage.success(data.success) : ElMessage.success('获取失败');
       content.router.push('/equips/list');
    }

    function Ok() {
      content.isId ? put() : create();
    }

    onMounted(() => {
      restaurants.value = loadAll();
      if (content.isId) getById();
    })

    const refContent = toRefs(content);

    return {
      ...refContent,
      uploadUrl,
      querySearch,
      Ok,
    }
  }
})

// 带输入建议 input 的代码片段
function autocomplete (){
    const restaurants = ref([]);

    // 带输入建议 input
    const querySearch = (queryString, cb) => {
      var results = queryString ?
      restaurants.value.filter(createFilter(queryString)):
      restaurants.value;
      cb(results);
    }

    const loadAll = () => {
      return [
        { value: '攻击' },
        { value: '法术' },
        { value: '防御' },
        { value: '移动' },
        { value: '打野' },
        { value: '游走' },
      ]
    }

    const createFilter = (queryString) => {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    };

    return {
      restaurants, loadAll, querySearch
    }
  }
</script>

<style lang="scss" scoped>
.equip_edit {
  .el-upload {
    img {
      display: inline-block;
      width: 100%;
    }
  }
}
</style>